package com.leoren.run.activity.myself;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.leoren.run.R;
import com.leoren.run.common.ResponseCode;
import com.leoren.run.common.ServerResponse;
import com.leoren.run.common.UrlConstants;
import com.leoren.run.dbbean.UserDB;
import com.leoren.run.log.L;
import com.leoren.run.utils.GsonUtil;
import com.leoren.run.utils.Http.OkHttp.CommonOkHttpClient;
import com.leoren.run.utils.Http.OkHttp.exception.OkHttpException;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataHandle;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataListener;
import com.leoren.run.utils.Http.OkHttp.request.CommonRequest;
import com.leoren.run.utils.StringUtils;
import com.leoren.run.utils.ToastUtil;
import com.leoren.run.vo.User;

import org.litepal.LitePal;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 更新邮箱界面
 */
public class UpdateEmailActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private EditText emailText;
    private Button finishBtn;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_email);

        initLayout();
    }

    /**
     * 初始化控件
     */
    private void initLayout(){
        toolbar = findViewById(R.id.update_email_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        emailText = findViewById(R.id.update_email_text);
        finishBtn = findViewById(R.id.finish_update_email_btn);
        finishBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.finish_update_email_btn:
                updateEmail();
                break;
            default:
                break;
        }

    }

    /**
     * 网络请求进行邮箱更新
     * @return
     */
    private int updateEmail(){
        String emailStr = emailText.getText().toString().trim();
        if(StringUtils.isBlank(emailStr)){
            ToastUtil.MakeToast("邮箱不能为空");
            return 0;
        }
        final UserDB userDB = LitePal.findFirst(UserDB.class);
        if(userDB == null){
            ToastUtil.MakeToast("网络错误，请重新登陆后再试");
            return 0;
        }
        showProgressDialog();
        RequestBody body = new FormBody.Builder()
                .add("id", String.valueOf(userDB.getTagId()))
                .add("email", emailStr)
                .build();
        final Request request = CommonRequest.createPostRequest(UrlConstants.USER_UPDATE_EMAIL, body);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(final String responseStr) {
                closeProgressDialog();
                L.e(responseStr +" Login");
                ServerResponse<User> response = GsonUtil.formatJsonToResponseUser(responseStr);
                if(response == null){
                    onFailure(new OkHttpException(ResponseCode.NETWORK_ERROR.getCode(), ResponseCode.NETWORK_ERROR.getValue()));
                    return;
                }
                if(!response.isSuccess()){
                    onFailure(new OkHttpException(ResponseCode.UNKNOWN_ERROR.getCode(), response.getMsg()));
                    return;
                }
                if (response.getStatus() == ResponseCode.SUCCESS.getCode()) {
                    User user = response.getData();
                    userDB.setEmail(user.getEmail());
                    userDB.update(userDB.getTagId());
                }
                ToastUtil.MakeToast(response.getMsg());
                UpdateEmailActivity.this.finish();
            }

            @Override
            public void onFailure(OkHttpException e) {
                closeProgressDialog();
                ToastUtil.MakeToast(e.getMsg() + "");

            }
        }));
        return 0;
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog(){
        if(progressDialog == null){
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog != null){
            progressDialog.dismiss();
        }
    }
}
